import 'dart:convert';
import 'package:http/http.dart' as http;

import '../models/user.dart';
import '../models/pet.dart';
import '../models/video.dart';
import '../models/post.dart';

class ApiService {
  static const String baseUrl = 'https://jsonplaceholder.typicode.com';
  
  // 获取用户列表
  Future<List<User>> getUsers() async {
    try {
      final response = await http.get(Uri.parse('$baseUrl/users'));
      if (response.statusCode == 200) {
        List<dynamic> data = json.decode(response.body);
        return data.map((json) => User.fromJson(json)).toList();
      } else {
        throw Exception('Failed to load users');
      }
    } catch (e) {
      throw Exception('Error fetching users: $e');
    }
  }
  
  // 获取用户详情
  Future<User> getUser(int userId) async {
    try {
      final response = await http.get(Uri.parse('$baseUrl/users/$userId'));
      if (response.statusCode == 200) {
        return User.fromJson(json.decode(response.body));
      } else {
        throw Exception('Failed to load user');
      }
    } catch (e) {
      throw Exception('Error fetching user: $e');
    }
  }
  
  // 获取宠物列表 (使用photos作为模拟数据)
  Future<List<Pet>> getPets({int limit = 20}) async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl/photos?_limit=$limit')
      );
      
      if (response.statusCode == 200) {
        List<dynamic> data = json.decode(response.body);
        return data.map((json) => Pet.fromJson(json)).toList();
      } else {
        throw Exception('Failed to load pets');
      }
    } catch (e) {
      throw Exception('Error fetching pets: $e');
    }
  }
  
  // 获取宠物详情
  Future<Pet> getPet(int petId) async {
    try {
      final response = await http.get(Uri.parse('$baseUrl/photos/$petId'));
      
      if (response.statusCode == 200) {
        return Pet.fromJson(json.decode(response.body));
      } else {
        throw Exception('Failed to load pet');
      }
    } catch (e) {
      throw Exception('Error fetching pet: $e');
    }
  }
  
  // 获取视频列表 (使用photos作为模拟数据)
  Future<List<Video>> getVideos({int limit = 20}) async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl/photos?_limit=$limit')
      );
      
      if (response.statusCode == 200) {
        List<dynamic> data = json.decode(response.body);
        return data.map((json) => Video.fromJson(json)).toList();
      } else {
        throw Exception('Failed to load videos');
      }
    } catch (e) {
      throw Exception('Error fetching videos: $e');
    }
  }
  
  // 获取视频详情
  Future<Video> getVideo(int videoId) async {
    try {
      final response = await http.get(Uri.parse('$baseUrl/photos/$videoId'));
      
      if (response.statusCode == 200) {
        return Video.fromJson(json.decode(response.body));
      } else {
        throw Exception('Failed to load video');
      }
    } catch (e) {
      throw Exception('Error fetching video: $e');
    }
  }
  
  // 获取帖子列表
  Future<List<Post>> getPosts({int limit = 20}) async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl/posts?_limit=$limit')
      );
      
      if (response.statusCode == 200) {
        List<dynamic> data = json.decode(response.body);
        return data.map((json) => Post.fromJson(json)).toList();
      } else {
        throw Exception('Failed to load posts');
      }
    } catch (e) {
      throw Exception('Error fetching posts: $e');
    }
  }
  
  // 获取帖子详情
  Future<Post> getPost(int postId) async {
    try {
      final response = await http.get(Uri.parse('$baseUrl/posts/$postId'));
      
      if (response.statusCode == 200) {
        return Post.fromJson(json.decode(response.body));
      } else {
        throw Exception('Failed to load post');
      }
    } catch (e) {
      throw Exception('Error fetching post: $e');
    }
  }
  
  // 获取帖子评论
  Future<List<dynamic>> getComments(int postId) async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl/posts/$postId/comments')
      );
      
      if (response.statusCode == 200) {
        return json.decode(response.body);
      } else {
        throw Exception('Failed to load comments');
      }
    } catch (e) {
      throw Exception('Error fetching comments: $e');
    }
  }
  
  // 获取用户关注列表
  Future<List<User>> getUserFollowing(String userId) async {
    await Future.delayed(Duration(milliseconds: 800));
    
    // 模拟数据
    final List<User> users = [];
    
    // 添加10个模拟用户
    for (int i = 1; i <= 10; i++) {
      users.add(
        User(
          id: 'user_$i',
          username: '用户${i + 100}',
          avatar: 'https://randomuser.me/api/portraits/${i % 2 == 0 ? 'men' : 'women'}/${i + 10}.jpg',
          bio: i % 3 == 0 ? '热爱宠物的${i % 2 == 0 ? '铲屎官' : '猫奴'}' : null,
          statistics: {
            'pets': i % 5,
            'posts': i * 3,
            'videos': i,
          },
        ),
      );
    }
    
    return users;
  }
  
  // 获取用户粉丝列表
  Future<List<User>> getUserFollowers(String userId) async {
    await Future.delayed(Duration(milliseconds: 800));
    
    // 模拟数据
    final List<User> users = [];
    
    // 添加8个模拟用户作为粉丝
    for (int i = 1; i <= 8; i++) {
      users.add(
        User(
          id: 'user_${i + 20}',
          username: '粉丝${i + 200}',
          avatar: 'https://randomuser.me/api/portraits/${i % 2 == 0 ? 'women' : 'men'}/${i + 30}.jpg',
          bio: i % 2 == 0 ? '喜欢关注有趣的宠物内容' : null,
          statistics: {
            'pets': i % 3,
            'posts': i * 2,
            'videos': i % 4,
          },
        ),
      );
    }
    
    return users;
  }
} 